/**
 *Project: jh-frameworks
 *File: cn.xkshow.util.converters.DateConverter.java 
 *Author: hardy(admin@xkshow.cn) Copyright
 ****************************************************************
 *   VERSION       DATE            BY       CHANGE/COMMENT
 * --------------------------------------------------------------
 *    1.0        2013-10-9         hardy         create
 ****************************************************************
 *note:
 ***************************************************************/ 
package cn.xkshow.util.converters;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang.StringUtils;

import cn.xkshow.util.DateHelper;

public class DateConverter implements Converter {

	@Override
	public Object convert(Class type, Object value) {
		// TODO Auto-generated method stub
		if (value == null)
	    {
	      return null;
	    }
	    if (type == Timestamp.class)
	    {
	      return convertToDate(type, value, DateHelper.getDateTimePattern());
	    }
	    if (type == Date.class)
	    {
	      return convertToDate(type, value, DateHelper.getDatePattern());
	    }
	    if (type == String.class)
	    {
	      return convertToString(type, value);
	    }

	    throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
	}
	
	protected Object convertToDate(Class type, Object value, String pattern)
	  {
	    DateFormat df = new SimpleDateFormat(pattern);
	    if ((value instanceof String))
	    {
	      try
	      {
	        if (StringUtils.isEmpty(value.toString()))
	        {
	          return null;
	        }

	        Date date = df.parse((String)value);
	        if (type.equals(Timestamp.class))
	        {
	          return new Timestamp(date.getTime());
	        }
	        return date;
	      }
	      catch (Exception pe)
	      {
	        pe.printStackTrace();
	        throw new ConversionException("Error converting String to Date");
	      }
	    }

	    throw new ConversionException("Could not convert " + value.getClass().getName() + " to " + type.getName());
	  }

	  protected Object convertToString(Class type, Object value)
	  {
	    if ((value instanceof Date))
	    {
	      DateFormat df = new SimpleDateFormat(DateHelper.getDatePattern());
	      if ((value instanceof Timestamp))
	      {
	        df = new SimpleDateFormat(DateHelper.getDateTimePattern());
	      }

	      try
	      {
	        return df.format(value);
	      }
	      catch (Exception e)
	      {
	        e.printStackTrace();
	        throw new ConversionException("Error converting Date to String");
	      }

	    }

	    return value.toString();
	  }

}
